<template :key="tableName">
  <page-header-wrapper>
    <a-card :bordered="false">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24" v-for="(qc, index) in queryColumnList" :key="qc.id">
              <a-form-item :label="qc.name" v-if="advanced || index < 2">
                <!-- 此处 htmlType 与/views/free/column/modules/CreateForm中的类型选项 对应 -->
                <!-- 选择框 -->
                <template v-if="['select', 'radio', 'checkbox'].includes(qc.htmlType)">
                  <a-select
                    :mode="qc.queryType === 'BETWEEN' ? 'multiple' : 'default'"
                    style="width: 100%"
                    placeholder="请选择"
                    v-model="qc.value"
                  >
                    <a-select-option v-for="(d, index) in dictData[qc.dictId]" :key="index" :value="d.dictValue">
                      {{ d.dictLabel }}
                    </a-select-option>
                  </a-select>
                </template>
                <!-- 日期选择 -->
                <template v-else-if="qc.htmlType === 'date'">
                  <a-range-picker
                    v-if="qc.queryType === 'BETWEEN'"
                    v-model="qc.value"
                    :show-time="{ format: 'HH:mm' }"
                    format="YYYY-MM-DD HH:mm"
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    :placeholder="['Start Time', 'End Time']"
                  />
                  <a-date-picker
                    v-else
                    v-model="qc.value"
                    show-time
                    valueFormat="YYYY-MM-DD HH:mm:ss"
                    placeholder="Select Time"
                  />
                </template>
                <!-- 文本框 -->
                <a-input v-else v-model="qc.value" placeholder="请输入" allow-clear/>
              </a-form-item>
            </a-col>
            <a-col :md="!advanced && 8 || 24" :sm="24" v-if="queryColumnList.length > 0">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px" v-if="queryColumnList.length > 2">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 数据展示 -->
      <table-layout
        :permPrefix="permPrefix"
        :columnList="columnList"
        :dataSource="dataSource"
        :dictData="dictData"
        @add="$refs.createForm.handleAdd()"
        @update="id => $refs.createForm.handleUpdate(id)"
        @delete="ids => handleDelete(ids)"
        @export="handleExport"
      />
      <!-- 增加修改 -->
      <create-form
        ref="createForm"
        :tableName="tableName"
        :dictData="dictData"
        :formJson="formJson"
        @ok="resetQuery"
      />
      <!-- 分页 -->
      <a-pagination
        class="ant-table-pagination"
        show-size-changer
        show-quick-jumper
        :current="queryParam.pageNum"
        :total="total"
        :page-size="queryParam.pageSize"
        :showTotal="total => `共 ${total} 条`"
        @showSizeChange="onShowSizeChange"
        @change="changeSize"
      />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { mapActions } from 'vuex'
import { getTable } from '@/api/free/table'
import { listData, delData } from '@/api/free/data'
import { getMenu } from '@/api/system/menu'
import TableLayout from './page/TableLayout'
import CreateForm from './modules/CreateForm'
// import { downLoadExcel } from '@/utils/fileDownload'

export default {
  name: 'FreeData',
  components: {
    TableLayout,
    CreateForm
  },
  props: {
    tableName: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      tableInfo: {},
      columnList: [],
      // 需要字典转换的字段
      columnCodeDict: [],
      // 需要日期格式化的字段
      columnCodeDate: [],
      formJson: {},
      list: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      ids: [],
      loading: false,
      total: 0,
      // 数据字典集合 {dictType: [{label, value}]}
      dictData: {},
      queryParam: {
        pageNum: 1,
        pageSize: 10
      },
      // 权限前缀
      permPrefix: ''
    }
  },
  filters: {
  },
  created () {
  },
  computed: {
      /* 搜索条件列表 */
      queryColumnList () {
          return this.columnList.filter(item => item.queryType)
      },
      dictOptionMap () {
        let r = {}
        Object.keys(this.dictData).forEach(key => {
          r[key] = this.dictData[key].reduce((accumulator, current) => {
            accumulator['key_' + current.value] = current.label
            return accumulator;
          }, {});
        })
        return r
      },
      dataSource () {
        let r = []
        this.list.forEach(item => {
          this.columnList.forEach(col => {
            if (['select', 'radio', 'checkbox'].includes(col.htmlType)) {
              item[col.codeHump] = this.optionFormat(col.dictId, item[col.codeHump])
            } else if ('date' == col.htmlType) {
              item[col.codeHump] = this.parseTime(item[col.codeHump])
            }
          })
          r.push(item)
        })
        return r
      }
  },
  mounted () {
    this.permPrefix = `freeData:${this.tableName}:`
    this.loadTableInfo()
  },
  methods: {
    ...mapActions(['GetPageCache', 'SetPageCache']),
    /* 加载动态表信息 */
    loadTableInfo () {
      if (!this.tableName) {
        return
      }
      this.GetPageCache(this.tableName).then(pageCache => {
        if (pageCache) {
          this.list = pageCache.list
          this.total = pageCache.total
          this.advanced = pageCache.advanced
          this.queryParam.pageNum = pageCache.pageNum
          this.queryParam.pageSize = pageCache.pageSize
        } else {
          this.getList()
        }
      })
      
      getTable(this.tableName).then(response => {
        this.tableInfo = response
        const { tableLabel, menuName, columnList, dictData, formJson } = response
        // 浏览器刷新后 会丢失标签页标题        
        if (this.$route.meta.title === '正在加载') {
          this.$route.meta.title = (menuName == null || menuName === 'null') ? tableLabel : menuName
        }
        
        this.columnList = (columnList || []).map(col => {
          col.codeHump = this.toHump(col.code)
          return col
        })
        this.dictData = dictData || {}

        if(formJson) {
          this.formJson = JSON.parse(formJson)
        }
      })
    },
    /** 构造查询条件 */
    buildQueryList () {
      return this.queryColumnList.filter(item => item.value).map(item => {
        return {
          code: item.code,
          queryType: item.queryType,
          htmlType: item.htmlType,
          value: item.value
        }
      })
    },
    /** 查询部门列表 */
    getList () {
      this.loading = true
      // 构造查询条件
      let queryList = this.buildQueryList()

      listData(this.tableName, this.queryParam, { queryList }).then(response => {
        this.loading = false
        const { list, total } = response
        this.total = total
        this.list = list || []

        this.SetPageCache({
          tableName: this.tableName,
          list: this.list,
          total: this.total,
          advanced: this.advanced,
          pageNum: this.queryParam.pageNum,
          pageSize: this.queryParam.pageSize
        })
      })
    },
    // 字典翻译
    optionFormat (dictId, text) {
      if (text) {
        const dict = this.dictOptionMap[dictId]
        if (dict) {
          return text.split(',').map(item => dict['key_' + item] || item).join(',')
        }
        return text
      }
      return ''
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParam.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.queryColumnList.forEach(item => {
        item.value = ''
      })
      this.queryParam = {
        pageNum: 1,
        pageSize: 10
      }
      this.handleQuery()
    },
    onShowSizeChange (current, pageSize) {
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    changeSize (current, pageSize) {
      this.queryParam.pageNum = current
      this.queryParam.pageSize = pageSize
      this.getList()
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    /** 删除按钮操作 */
    handleDelete (ids) {
      const that = this
      this.$confirm({
        title: '确认删除所选中数据?',
        content: '当前选中编号为 ' + ids + ' 的数据',
        onOk () {
          return delData(that.tableName, ids)
            .then(() => {
              that.getList()
              that.$message.success(
                '删除成功',
                3
              )
          })
        },
        onCancel () {}
      })
    },
    /** 导出按钮操作 */
    handleExport () {
      this.$confirm({
        title: '是否确认导出?',
        content: '此操作将导出当前条件下所有数据而非选中数据',
        onOk: () => {
          const queryList = this.buildQueryList()
          const url = `freeData/${this.tableName}/export`
          this.download(url, {
            queryList: JSON.stringify(queryList)
          }, `${this.tableName}_${new Date().getTime()}.xlsx`)
        },
        onCancel () {}
      })
    }
  }
}
</script>
